﻿using EnvDTE;
using EnvDTE80;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Project = EnvDTE.Project;

namespace LanguageExt
{
    [Command(PackageIds.MyCommand)]
    internal sealed class MyCommand : BaseCommand<MyCommand>
    {
        protected override async Task ExecuteAsync(OleMenuCmdEventArgs e)
        {
            // await VS.MessageBox.ShowWarningAsync("LanguageExt", "Button clicked");


            SolutionHelper solutionHelper = new SolutionHelper();
            List<string> solutionFiles = await solutionHelper.GetAllFilesInSolutionAsync();

            List<ChineseCharacterInfo> chineseCharacters = new List<ChineseCharacterInfo>();

            foreach (string file in solutionFiles)
            {
                if (Path.GetExtension(file).Equals(".cs"))
                {
                    FindChineseCharacters(file, chineseCharacters);
                }
            }

            ExportToExcel(chineseCharacters);
        }




        private void FindChineseCharacters(string filePath, List<ChineseCharacterInfo> chineseCharacters)
        {
            // string chinesePattern = @"[\u4e00-\u9fa5]+";
            string chinesePattern = @"[\p{IsCJKUnifiedIdeographs}]"; // 匹配中文字符
            var regex = new Regex(chinesePattern);

            string[] lines = File.ReadAllLines(filePath, Encoding.UTF8);
            for (int i = 0; i < lines.Length; i++)
            {
                var matches = regex.Matches(lines[i]);
                if (matches.Count > 0)
                {
                    string chineseText = string.Concat(matches.OfType<Match>().Select(m => m.Value));

                    chineseCharacters.Add(new ChineseCharacterInfo
                    {
                        FileName = filePath,
                        LineNumber = i + 1,
                        ChineseText = chineseText
                    });
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        private void ExportToExcel(List<ChineseCharacterInfo> data)
        {
            IWorkbook workbook = new XSSFWorkbook();
            ISheet sheet = workbook.CreateSheet("ChineseCharacters");

            IRow headerRow = sheet.CreateRow(0);
            headerRow.CreateCell(0).SetCellValue("文件名");
            headerRow.CreateCell(1).SetCellValue("行号");
            headerRow.CreateCell(2).SetCellValue("中文字符");

            for (int i = 0; i < data.Count; i++)
            {
                IRow row = sheet.CreateRow(i + 1);
                row.CreateCell(0).SetCellValue(data[i].FileName);
                row.CreateCell(1).SetCellValue(data[i].LineNumber);
                row.CreateCell(2).SetCellValue(data[i].ChineseText);
            }

            using (FileStream stream = new FileStream("ChineseCharacters.xlsx", FileMode.Create, FileAccess.Write))
            {
                workbook.Write(stream);
            }
        }


    }
}




/// <summary>
/// 
/// </summary>
public class ChineseCharacterInfo
{
    public string FileName { get; set; }
    public int LineNumber { get; set; }
    public string ChineseText { get; set; }
}


public class SolutionHelper
{
    public async Task<List<string>> GetAllFilesInSolutionAsync()
    {
        await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

        DTE2 dte = Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(DTE)) as DTE2;
        List<string> allFiles = new List<string>();

        foreach (Project project in dte.Solution.Projects)
        {
            GetFilesFromProject(project, allFiles);
        }

        return allFiles;
    }

    private void GetFilesFromProject(Project project, List<string> allFiles)
    {
        if (project == null || project.ProjectItems == null)
            return;

        foreach (ProjectItem item in project.ProjectItems)
        {
            ProcessProjectItem(item, allFiles);
        }
    }

    private void ProcessProjectItem(ProjectItem item, List<string> allFiles)
    {
        if (item == null)
            return;

        if (item.Kind == EnvDTE.Constants.vsProjectItemKindPhysicalFile)
        {
            string filePath = item.FileNames[1];
            if (File.Exists(filePath))
            {
                allFiles.Add(filePath);
            }
        }

        if (item.ProjectItems != null)
        {
            foreach (ProjectItem subItem in item.ProjectItems)
            {
                ProcessProjectItem(subItem, allFiles);
            }
        }
    }
}
